﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DynamicChart.Web.Models
{
    public class DynamicChartService
    {
        public List<InternalDataSource> GetInternalDataSources()
        {
            using (DynamicChartDbContext context = new DynamicChartDbContext())
            {
                return context.Set<InternalDataSource>().ToList();
            }
        }

        public bool SaveInternalDataSource(InternalDataSource dataSource)
        {
            using (DynamicChartDbContext context = new DynamicChartDbContext())
            {
                if (string.IsNullOrEmpty(context.Set<InternalDataSource>()
                    .Where(p => p.Name == dataSource.Name)
                    .Select(p => p.Name).SingleOrDefault()))
                {
                    context.Set<InternalDataSource>().Add(dataSource);
                }
                else
                {
                    context.Entry(dataSource).State = System.Data.Entity.EntityState.Modified;
                }

                if (context.SaveChanges() > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public bool DeleteInternalDataSource(InternalDataSource dataSource)
        {
            using (DynamicChartDbContext context = new DynamicChartDbContext())
            {
                if (!string.IsNullOrEmpty(context.Set<InternalDataSource>()
                    .Where(p => p.Name == dataSource.Name)
                    .Select(p => p.Name).SingleOrDefault()))
                {
                    context.Entry(dataSource).State = System.Data.Entity.EntityState.Deleted;
                }

                if (context.SaveChanges() > 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
}